import React, { useEffect, useState } from 'react';

const SvgPlatform = ({ row, col, cellSize, gap, name, index, updatePlatform, deleteMode, deletePlatform }) => {
  const x = (col + 0.5) * (cellSize + gap);
  const y = (row + 0.0) * (cellSize + gap);
  const width = 2.5 * cellSize;
  const height = 1.7 * cellSize;

  const [editing, setEditing] = useState(false);
  const [inputValue, setInputValue] = useState(name);

  const handleConfirm = () => {
    updatePlatform(index, { row, col, name: inputValue });
    setEditing(false);
  };

  const handleClick = () => {
    if (deleteMode) {
      deletePlatform(index);
    } else {
      setEditing(true);
    }
  };

  return (
    <g transform={`translate(${x}, ${y})`}>
      <rect
        x={-width / 2}
        y={-height / 2}
        width={width}
        height={height}
        fill="#ccc"
        stroke="#000"
        strokeWidth="2"
        rx="2"
        ry="2"
        onClick={handleClick}
      />
      {editing ? (
        <foreignObject x={-width / 2} y={height / 2 - 22} width={width} height={20}>
          <input
            type="text"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onBlur={handleConfirm}
            onKeyDown={(e) => {
              if (e.key === 'Enter') handleConfirm();
            }}
            style={{ width: '100%', fontSize: '10px' }}
            autoFocus
          />
        </foreignObject>
      ) : (
        <text
          x="0"
          y="2"
          textAnchor="middle"
          fontSize="14"
          fill="#000"
          dominantBaseline="middle"
          onClick={handleClick}
          style={{ cursor: 'pointer' }}
        >
          {name}
        </text>
      )}
    </g>
  );
};

const Platforms = React.memo(({ platformsState, cellSize, gap, updatePlatformsState, deleteMode, drawPlatformMode, setDrawPlatformMode }) => {
    const [platforms, setPlatforms] = useState([]);
  
    useEffect(() => {
      if (platformsState) {
        setPlatforms(platformsState);
      }
    }, [platformsState]);
  
    const updatePlatform = (index, updated) => {
      const next = [...platforms];
      next[index] = updated;
      setPlatforms(next);
      updatePlatformsState(next);
    };
  
    const deletePlatform = (index) => {
      const next = platforms.filter((_, i) => i !== index);
      setPlatforms(next);
      updatePlatformsState(next);
    };
  
    const handleGridClick = (row, col) => {
      if (drawPlatformMode) {
        const exists = platforms.some(p => p.row === row && p.col === col);
        if (!exists) {
          const newPlatform = { row, col, name: "New Platform" };
          const next = [...platforms, newPlatform];
          setPlatforms(next);
          updatePlatformsState(next);
        }
        setDrawPlatformMode(false); // 自动退出新增模式
      }
    };
  
    return (
      <g>
        {/* 捕获格点点击用于新增站台 */}
        {drawPlatformMode && Array.from({ length: 1000 }).map((_, index) => {
          const row = Math.floor(index / 100);
          const col = index % 100;
          return (
            <rect
              key={index}
              x={col * (cellSize + gap)}
              y={row * (cellSize + gap)}
              width={cellSize}
              height={cellSize}
              fill="transparent"
              stroke="transparent"
              onClick={() => handleGridClick(row, col)}
            />
          );
        })}
  
        {platforms.map((platform, index) => (
          <SvgPlatform
            key={index}
            row={platform.row}
            col={platform.col}
            name={platform.name}
            cellSize={cellSize}
            gap={gap}
            index={index}
            updatePlatform={updatePlatform}
            deletePlatform={deletePlatform}
            deleteMode={deleteMode}
          />
        ))}
      </g>
    );
  });
  
  export default Platforms;
  